import java.io.*;
import java.util.*;

/**
 *手机卡工具类
 */
@SuppressWarnings("unused")
public class CardUtils {
    Map<String, MoBileCard> cards=new HashMap<String, MoBileCard>();
    Map<String, List<ConSumInTo>> consumIntos=new HashMap<String,List<ConSumInTo>>();
    List<Scene> scenes=new ArrayList<Scene>();
    /**
     * 初始化用户
     */
    public  void  init(){
       MoBileCard card1=new MoBileCard("何洛洛","123456","135877452",
               new TackPackage(),58.0,42);
        MoBileCard card2 = new MoBileCard("黄露露", "123", "13956712467",
                new NetPackage(), 68.0, 32.0);
        MoBileCard card3 = new MoBileCard("朱蓉蓉", "123", "13911568956",
                new SuperPackage(), 78.0, 22.0);
        MoBileCard card4 = new MoBileCard("桃跑跑", "123", "13924221868",
                new TackPackage(), 78.0, 2.0);
           card4.setConsumAmount(98.0);
           card4.setRealTalkTime(500);
           card4.setRealSMSCount(100);
           cards.put("123456789",card1);
           cards.put("123456789",card2);
           cards.put("123456789",card3);
           cards.put("123456789",card4);
    }
    /**
     * 场景初始化
     */
    public void initScenes(){
        scenes.add(new Scene("通话",90,"问候客户，谁知其如此难缠 通话90分钟"));
        scenes.add(new Scene("通话",30,"询问妈妈身体状况 本地通话30分钟"));
        scenes.add(new Scene("短信",5,"参与环境保护实施方案问卷调查 发送短信5条"));
        scenes.add(new Scene("短信",50,"通知朋友手机换号，发送短信50条"));
        scenes.add(new Scene("上网",1*1024,"和女友微信视频聊天   使用流量1G"));
        scenes.add(new Scene("上网",2*1024,"晚上手机在线看韩剧，不留神睡着啦！ 使用流量 2G"));
    }

    /**
     * 判断是否存在此卡用户
     * @param number
     * @param passWord
     * @return
     */
    public boolean isExistCard(String number, String passWord) {
        Set<String> numbers = cards.keySet();
        Iterator<String> it = numbers.iterator();
        while (it.hasNext()) {
            String searchNum = it.next();
            if (searchNum.equals(number)
                    && (cards.get(searchNum)).getPassWord().equals(passWord)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 查询指定卡号是否注册
     * @param searchNumber
     * @return
     */
    public boolean isExistCard(String searchNumber) {
        Set<String> numbers = cards.keySet();
        for (String number : numbers) {
            if (number.equals(searchNumber)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 生成一个十一位手机号字符串  不重复
     * @return
     */
     public  String creatNumber(){
         Random random=new Random();
         boolean isExistCard=false;
         String number="";
         int temp=0;
         do {
            isExistCard=false;// 标志位重置为false,用于控制外重循环，当生成了
             // 生成的随机数是8位 不能小于10000000，否则重新生成
             do {
                 temp=random.nextInt(100000000);

             }while (temp<10000000);
             number="139"+temp;
             // 和现有用户的卡号比较，不能是重复
             Set<String> numbers=cards.keySet();
             for (String cardNumbers:numbers){
                 if (number.equals(cardNumbers)){
                     isExistCard=true;
                     break;
                 }
             }

         }while (isExistCard);
         return number;
     }

    /**
     * 创建一个卡号列表
     * @param count  指定个数
     * @return 卡号列表
     */
     public String[] getNewNumber(int count){
         String[] numbers=new String[count];
         for (int i = 0; i <count ; i++) {
             numbers[i]=creatNumber();
         }
         return numbers;
     }

    /**
     * 注册新卡
     * @param card
     */
     public  void  addCard(MoBileCard card){
         cards.put(card.getCardNumber(),card);
         System.out.println("注册成功");
         card.showMeg();
     }

    /**
     * 退网项目
     * @param delnumber
     */
    public  void  delCard(String delnumber){
         if(isExistCard(delnumber)){
             cards.remove(delnumber);
             System.out.println("卡号"+delnumber+"办理退网成功");
         }else {
             System.out.println(delnumber+"卡号未注册，不能办理退网");
         }
    }
    /**
     * 查询套餐
     * @param searchNumber
     */
    public  void  showRemainDetail(String searchNumber){
        MoBileCard card;
        int remainTalkTime;
        int remainSmsCount;
        int remainFlow;
        StringBuffer meg=new StringBuffer();
        card=cards.get(searchNumber);
        meg.append("您的卡号是"+searchNumber+"套餐剩余为：\n");
        ServicePackage pack=card.getSerPackage();
        if (pack instanceof TackPackage){
            //向下转为话痨套餐
            TackPackage cardPack= (TackPackage) pack;
            // 话唠套餐，查询套餐内剩余的通话时长和短信条数
            remainTalkTime=cardPack.getTalkTime()>card.getRealTalkTime()?cardPack.getTalkTime()-card.getRealTalkTime():0;
            meg.append("通话时长"+remainTalkTime+"分钟");
            remainSmsCount=cardPack.getSmsCount()>card.getRealSMSCount()?cardPack.getSmsCount()-card.getRealSMSCount():0;
            meg.append("发送短信"+remainSmsCount+"条信息");

        }else if(pack instanceof NetPackage){
            //向下转型为网虫套餐
            NetPackage cardPack= (NetPackage) pack;
            remainFlow=cardPack.getFlwor()>card.getRealFlow()?cardPack.getFlwor()-card.getRealFlow():0;
            meg.append("使用流量"+ Common.dataFormat(remainFlow*1/1024)+"GB");

        }else  if(pack instanceof SuperPackage){
            //向下转为超人套餐
            SuperPackage cardPack = (SuperPackage) pack;
            // 超人套餐：查询套餐内剩余的通话时长、短信条数、上网流量
            remainTalkTime = cardPack.getTalkTime() > card
                    .getRealTalkTime() ? cardPack.getTalkTime()
                    - card.getRealTalkTime() : 0;
            meg.append("通话时长：" + remainTalkTime + "分钟\n");
            remainSmsCount = cardPack.getSmsCount() > card
                    .getRealSMSCount() ? cardPack.getSmsCount()
                    - card.getRealSMSCount() : 0;
            meg.append("短信条数：" + remainSmsCount + "条\n");
            remainFlow = cardPack.getFlwor() > card.getRealFlow() ? cardPack
                    .getFlwor() - card.getRealFlow() : 0;
            meg.append("上网流量：" + Common.dataFormat(remainFlow * 1.0 / 1024)
                    + "GB");
        }
        System.out.println(meg);
        }


    /**
     * 查询指定卡号本月消费订单
     * @param searchNumber
     */
    public  void  showAmountDetail(String searchNumber){
        MoBileCard card;
        StringBuffer meg=new StringBuffer();
        card=cards.get(searchNumber);
        meg.append("您的卡号为"+card.getCardNumber()+",当月账单为：\n");
        meg.append("套餐资费："+card.getSerPackage().getPrice()+"元\n");
        meg.append("合计："+Common.dataFormat(card.getMoney())+"元\n");
        //显示本月信息
        System.out.println(meg);


    }

    /**
     * 指定卡号更换套餐
     * @param number
     * @param packNum
     */
    public void changeingPack(String number, int packNum) {
        MoBileCard card; // 指定的手机卡
             ServicePackage pack; // 要换的套餐
              if (isExistCard(number)) {
                       card = cards.get(number);
                       // 获取要换的套餐对象
                      switch (packNum) {
                          case 1:
                               pack = new TackPackage();
                               break;
                          case 2:
                                  pack = new NetPackage();
                                   break;
                           default:
                               pack = new SuperPackage();
                                  break;
                            }
                       if (!(card.getSerPackage().getClass().getName().equals(pack.getClass().getName()))) {
                               // 该卡余额中减去当月套餐资费
                           if (card.getMoney() >= pack.getPrice()) {
                                            card.setMoney(card.getMoney() - pack.getPrice());
                                 // 换套餐
                                card.setSerPackage(pack);
                                 // 当月实际使用数据清零
                                 card.setRealTalkTime(0);
                                 card.setRealFlow(0);
                                   card.setRealSMSCount(0);
                                    // 当月消费金额设置为新套餐月资费
                                  card.setConsumAmount(pack.getPrice());
                                  System.out.print("更换套餐成功！");
                                  pack.showInTo();
                             } else {
                                   System.out.println("对不起，您的余额不足以支付新套餐本月资费，请充值后再办理更换套餐业务！");
                                   return;
                                }
                       } else {
                                System.out.println("对不起，您已经是该套餐用户，无需换套餐！");
                          }

                   } else {
                    System.out.println("对不起，该卡号未注册，不能换套餐！");
                   }
        }


    /**
     * 为指定卡号充值
     * @param number
     * @param money
     */
    public void chargeMoney(String number, double money) {
        MoBileCard card;
        if (money<0) {
            System.out.println("最少充值50元");
            return;
        }
        card=cards.get(number);
        card.setMoney(card.getMoney()+money);
        System.out.println("充值成功，您当前话费为"+Common.dataFormat(card.getMoney())+"元.");
    }

    /**
     * 为改手机号添加消费信息
     * @param number
     * @param info
     */
    public void addConsumInto(String number, ConSumInTo info){
        Set<String> numbers=consumIntos.keySet();
        Iterator<String> it=numbers.iterator();
        List<ConSumInTo> inTos=new ArrayList<ConSumInTo>();
        boolean isExist=false;//现存卡号中是否有此卡号消费记录 ture为真 false为否
        while (it.hasNext()){
            if(it.next().equals(number)){
                //由此卡消费记录n  那么遍历消费记录
                inTos=consumIntos.get(number);
                inTos.add(info);
                isExist=true;
                System.out.println("已添加一条记录");
                break;
            }
        }//没有此卡消费记录 则添加
        if(!isExist){
            inTos.add(info);
            consumIntos.put(number,inTos);
            System.out.println("不存在消费记录 已为您添加");
        }

    }

    /**
     * 打印消费信息
     * @param number
     */
    public void printConsumInfo(String number){
        Writer  fileWrite=null;
        try {
            fileWrite=new FileWriter("D:/11/a/消费记录.txt");
            Set<String> numbers = consumIntos.keySet();
            Iterator<String> it = numbers.iterator();
            List<ConSumInTo> infos = new ArrayList<ConSumInTo>();//存储指定卡所有消费记录
           boolean isExist = false; // 现有消费列表中是否存在此卡号消费记录，是：true 否：false
            while (it.hasNext()){
                if (it.next().equals(number)){
                    infos=consumIntos.get(number);
                    isExist=true;
                    break;
                }
            }
            if(isExist){
                //存在 则将打印消费记录到本地
                StringBuffer content=new StringBuffer("************"+number+"****消费记录\n");
                content.append("序号\t类型\t数据（上网（MB）/通话（分钟）/短信（条））\n");
                for (int i = 0; i <infos.size() ; i++) {
                        ConSumInTo into=infos.get(i);
                        content.append((i+1)+".\t\t"+into.getType()+"\t\t"+into.getConsumData()+"\n");

                }
                fileWrite.write(content.toString());
                fileWrite.flush();
                System.out.println("消费订单打印完毕");
            }else {
                System.out.println("不存在消费记录 无法打印");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileWrite!=null ){
                try {
                    fileWrite.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 使用搜搜
     * @param number 当前卡号
     */
    public void userSoso(String number) {
        MoBileCard card = cards.get(number);//获取此卡对象
        ServicePackage pack = card.getSerPackage(); // 获取此卡所属套餐
        Random random = new Random();
        int ranNum = 0;
        int temp = 0;  //记录各场景中实际消费数据
        do {
            ranNum = random.nextInt(6);//获取一个0-5随机数
            Scene scene = scenes.get(ranNum); //获取该序号所对应的场景
            switch (ranNum) {
                //序号为0或1为通话场景
                case 0:
                case 1:
                    if (pack instanceof CallSevice) {
                        // 执行通话方法
                        System.out.println(scene.getDescription());
                        CallSevice callService = (CallSevice) pack;
                        try {
                            temp = callService.call(scene.getData(), card);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        // 添加一条消费记录
                        addConsumInto(number, new ConSumInTo(number,
                                scene.getType(), temp));
                        break;
                    } else {
                        // 如果该卡套餐不支持通话功能，则重新生成随机数选择其他场景
                        continue;
                    }
                    //序号为2或3为发短信场景
                case 2:
                case 3:
                    // 判断该卡所属套餐是否支持短信功能
                    if (pack instanceof SendSevice) {
                        // 执行发短信方法
                        System.out.println(scene.getDescription());
                        SendSevice sendSevice = (SendSevice) pack;
                        try {
                            temp = sendSevice.send(scene.getData(), card);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        addConsumInto(number, new ConSumInTo(number, scene.getType(), temp));
                        break;
                    } else {
                        continue; // 如果该卡套餐不支持发短信功能，则重新生成随机数选择其他场景
                    }
                    //序号四五为上网场景
                case 4:
                case 5:
                    // 判断该卡所属套餐是否支持上网功能
                    if (pack instanceof NetSevice) {
                        //执行上网
                        System.out.println(scene.getDescription());
                        NetSevice netSevice = (NetSevice) pack;
                        try {
                            temp = netSevice.netPlay(scene.getData(), card);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        addConsumInto(number, new ConSumInTo(number, scene.getType(), temp));
                        break;
                    } else {
                        continue; // 如果该卡套餐不支持发短信功能，则重新生成随机数选择其他场景
                    }

            }
            break;

        } while (true);
    }

    /**
     * 按照套餐序号返回套餐对象
     * @param packId
     * @return
     */
    public ServicePackage createPack(int packId) {
        ServicePackage sv=null;
        switch (packId){
            case 1:
                sv=new TackPackage();
                break;
            case 2:
                sv=new NetPackage();
                break;
            case 3:
                sv=new SuperPackage();
                break;

        }
        return sv;
    }

    /**
     * 资费说明
     */
    public void showDescription(){
        Reader rd=null;
        try {
            rd=new FileReader("d:/11/a/套餐资费说明.txt");
            char[] content = new char[100000];
            int len = 0;
            StringBuffer sb = new StringBuffer();
            while((len=rd.read(content))!=-1){
                sb.append(content,0,len);  //拼接字符串
            }
            System.out.println(sb);

        }  catch (IOException e) {
            e.printStackTrace();
        }
    }




}


